/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controle;

import Modelo.Sala;
import Modelo.Sessao;
import Modelo.TableModelSala;
import Modelo.TableModelSessao;
import Visao.CinemaGUI;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 *
 * @author andreus & gabriel
 */
public class SessaoController {

    private CinemaGUI view;
    private TableModelSessao model;
    private static String arqSaida = "/home/andreus/NetBeansProjects/MVC/relatorio.csv";
    static BufferedWriter escritor;

    public SessaoController(CinemaGUI view, TableModelSessao model) {
        this.view = view;
        this.model = model;
    }

    public void remove() {
        int index = view.getTableSessoes().getSelectedRow();
        if (index == -1) {
            return;
        }
        model.remove(index);
    }

    public void insert() {
        Sessao s = newFromView();
        if (s != null) {
            model.add(s);
        }
    }

    public void update() {
        int index = view.getTableVendas().getSelectedRow();
        if (index == -1) {
            return;
        }
        Sessao s = model.select(index);
        if (s != null && s.getIngressos()!= s.getSala().getLotacao()) {
            s.setIngressos(s.getIngressos() + 1);
            model.update(index, s);
        }
    }

    public void print() throws IOException {
        if (view.getTableVendas().getRowCount() > 0) {
            escritor = new BufferedWriter(new FileWriter(arqSaida));
            for (int i = 0; i < model.getRowCount(); i++) {
                for (int j = 0; j < model.getColumnCount(); j++) {
                    escritor.write("" + model.getValueAt(i, j) + ",");
                }
                escritor.write("\n");
            }
            escritor.close();
        }
    }

    public void select() {
        int index = view.getTableSessoes().getSelectedRow();
        if (index == -1) {
            return;
        }
        Sessao s = model.select(index);
        view.getTxtNomeFilme().setText(s.getNome_filme());
        view.getTxtData().setText(s.getData());
        view.getTxtHora().setText(s.getHorario());
        view.getTxtIngressos().setText("" + s.getIngressos());
        view.getCmbSala().setSelectedItem(s.getSala().getNumero());
    }
    

    private Sessao newFromView() {
        try {
            Sessao sessao = new Sessao();
            sessao.setNome_filme(view.getTxtNomeFilme().getText());
            sessao.setData(view.getTxtData().getText());
            sessao.setHorario(view.getTxtHora().getText());
            sessao.setSala(view.getSalaSeleciona());
            return sessao;
        } catch (Exception e) {

            return null;
        }
    }
}
